/*
 * @描述: 登录注册找回密码API
 * @版权所有: 广东国星科技有限公司
 * @商业授权: www.mscodecloud.com
 */
import request from '@/utils/request';

export async function query() {
  return request('/api/account/users');
}

export async function getCurrentUser() {
  const mscode_token = localStorage.getItem('mscode_token');
  if (mscode_token) {
    return request('/api/uaa/users/getSysUser', {
      method: 'GET'
    });
  }
}

/** 登录注册找回密码API开始 */

export async function loginAccount(params) {
  params['scope'] = 'ui';
  if (params.smsCaptcha) {
    params['grant_type'] = 'mobile';
  } else {
    params['grant_type'] = 'password';
  }
  params['client_id'] = 'browser';
  const data = await request('/api/uaa/oauth/token', {
    method: 'POST',
    requestType: 'form',
    headers: { 'Authorization': 'Basic YnJvd3Nlcjo=', 'Content-Type': 'application/x-www-form-urlencoded' },
    data: params
  });
  if (data && !data.error) {
    localStorage.setItem('mscode_token', data.access_token);

    // 查询当前用户的授权菜单和按钮
    const currentAuthorityResponse = request(`/api/account/sysuserdetail/queryCurrentAuthority`, {
      method: 'POST',
      requestType: 'form',
      data: {
        username: params.username,
        mobile: params.mobile
      }
    });
    currentAuthorityResponse.then(data => {
      if (data) {
        localStorage.setItem('mscode_menu', JSON.stringify(data.menu));
        localStorage.setItem('mscode_menubutton', data.menuButton); // 当前用户的授权按钮隐藏项
      }
    });
    return currentAuthorityResponse;
  } else {
    localStorage.removeItem('mscode_token');
    localStorage.removeItem('mscode_menu');
    localStorage.removeItem('mscode_menubutton');
    localStorage.setItem('mscode_authority', 'guest');
  }
}

export async function registerAccount(params) {
  return request('/api/account/sysuserdetail/registerAccount', {
    method: 'POST',
    data: params
  });
}

export async function retrievePassword(params) {
  return request('/api/account/sysuserdetail/retrievePassword', {
    method: 'POST',
    requestType: 'form',
    data: {
      ...params
    }
  });
}

export async function compareCaptcha(params) {
  return request('/api/account/sysuserdetail/compareCaptcha', {
    method: 'POST',
    requestType: 'form',
    data: {
      ...params
    }
  });
}

export async function getSmsCaptcha(mobile) {
  return request(`/api/account/captcha/getSmsCaptcha?mobile=${mobile}`);
}

/** 登录注册找回密码API结束 */
